package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryShopType() {

        // 1. 直接查询redis
        String shopTypeJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);


        // 2. redis中能查询到直接返回商铺列表
        if(StrUtil.isNotBlank(shopTypeJson)){
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }

        // 3. redis未命中则需查询数据库
        List<ShopType> shopTypeList = query().list();


        // 4. 数据库未命中返回错误信息
        if(shopTypeList == null || shopTypeList.isEmpty()){
            return Result.fail("商铺列表不存在！");
        }

        // 5. 查询到则先写入redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));

        // 6. 返回商品列表
        return Result.ok(shopTypeList);
    }
}
